package org.lds.scheduled.job.client.service;

import org.lds.scheduled.job.client.enums.ClientErrorEnum;
import org.lds.scheduled.job.client.model.MethodCache;
import org.lds.scheduled.job.common.exception.BusinessException;
import org.lds.scheduled.job.common.exception.ExceptionMessage;
import org.lds.scheduled.job.common.model.dto.ResultDTO;
import org.lds.scheduled.job.common.model.request.ScheduledJobRequest;
import org.lds.scheduled.job.common.util.AssertUtil;
import org.lds.scheduled.job.common.util.ScheduledJobUtil;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

public class AbstractScheduledJobService implements ScheduledJobService {
    private Map<String, MethodCache> cache = new HashMap<>();
    public void initCache(Map<String, MethodCache> cache) {
        this.cache.putAll(cache);
    }

    @Override
    public ResultDTO common(ScheduledJobRequest request) {
        try {
            String key = ScheduledJobUtil.jobKey(request.getAppName(), request.getKey());
            MethodCache methodCache = cache.get(key);
            AssertUtil.assertTrue(Objects.nonNull(methodCache), ClientErrorEnum.JOB_KEY_NOT_EXIST);

            methodCache.getMethod().invoke(methodCache.getObj());
            return ResultDTO.success();
        } catch (BusinessException e) {
            ExceptionMessage exceptionMessage = e.getExceptionMessage();
            return ResultDTO.fail(exceptionMessage.getCode(), exceptionMessage.getMessage());
        } catch (Exception e) {
            return ResultDTO.fail(ClientErrorEnum.METHOD_INVOKE_FAIL);
        }
    }
}
